<template>
  <div class="login-bg">
    <div id="login-box">
      <!-- 右主 -->
      <div class="login-banner"></div>
      <el-form
        ref="forgetFormRef"
        :model="forgetData"
        :rules="forgetRules"
        class="login-form"
        auto-complete="on"
      >
        <div class="title-container">
          <h3 class="title">
            {{ $t("forget.title") }}
          </h3>
          <div class="zn">
            <span>
              <!--语言选择-->
              <el-tooltip content="语言切换" placement="top">
                <lang-select
                  class="setting-item"
                  style="font-size: 22px; cursor: pointer"
                />
              </el-tooltip>
            </span>
          </div>
        </div>
        <div>
          <!-- 手机号 -->
          <el-form-item prop="phone">
            <el-input
              v-model="forgetData.phone"
              :placeholder="$t('forget.phone')"
              tabindex="1"
              autocomplete="on"
            >
              <template #prefix>
                <svg-icon icon-class="phone" />
              </template>
            </el-input>
          </el-form-item>
          <!-- 数字验证码 -->
          <el-form-item prop="verifyCode">
            <el-input
              v-model="captchaLogin.verifyCode"
              auto-complete="off"
              :placeholder="$t('reset.verifyCode')"
              class="w-[60%]"
            >
              <template #prefix>
                <svg-icon icon-class="verify_code" />
              </template>
            </el-input>

            <div class="captcha">
              <img v-throttle="getCaptcha" :src="captchaBase64" />
            </div>
          </el-form-item>
          <!-- 手机验证码 -->
          <el-form-item prop="smsCode">
            <el-input
              v-model="forgetData.smsCode"
              :placeholder="$t('smslogin.captcha')"
            >
              <template #prefix>
                <svg-icon icon-class="verify_code" />
              </template>
              <template #append>
                <span
                  v-if="mobileCodeTimer <= 0"
                  v-throttle="getSmsCode"
                  class="getMobileCode"
                  style="cursor: pointer"
                >
                  {{ $t("smslogin.fscaptcha") }}
                </span>
                <span
                  v-if="mobileCodeTimer > 0"
                  class="getMobileCode"
                  style="cursor: pointer"
                >
                  {{ mobileCodeTimer }}秒后可重新获取
                </span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 新密码 -->
          <el-form-item prop="password">
            <el-input
              v-model="forgetData.password"
              type="password"
              :placeholder="$t('forget.newpassword')"
              tabindex="3"
              autocomplete="on"
              show-password
              class="einput"
              @focus="changePasswordTip(true)"
              @blur="changePasswordTip(false)"
            >
              <template #prefix>
                <svg-icon icon-class="password" />
              </template>
            </el-input>
            <span v-if="isShowTip" class="poptip"
              >仅支持字母、数字和下划线组合！!</span
            >
          </el-form-item>
        </div>
        <!-- 确认忘记密码 -->
        <el-button
          v-throttle="handleReset"
          :loading="loading"
          type="primary"
          size="large"
          style="width: 100%; margin-top: 35px"
        >
          {{ $t("forget.ok") }}
        </el-button>
        <div class="sub-link">
          <el-link v-throttle="login" type="primary" :underline="false">
            {{ $t("forget.login") }}
          </el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
// 路由
import router from "@/router";
import { FormRules } from "element-plus";
import { forgetData, phoneLoginDatato } from "@/api/auth/types";
import { getCaptchaApi, getPhoneCaptchaApi } from "@/api/auth";
// 状态管理依赖
import { useUserStore } from "@/store/modules/user";

const isShowTip = ref(false);
const userStore = useUserStore();
// 重置密码
const forgetFormRef = ref(ElForm);
// 确认按钮等待
const loading = ref(false);
// 获取手机验证码 图片倒计时
const mobileCodeTimer = ref(0);
const forgetData = ref<forgetData>({
  phone: "",
  password: "",
  smsCode: "",
});
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 验证码判断请求数据
let captchaLogin = ref<phoneLoginDatato>({
  phone: "",
});
const forgetRules = ref<FormRules>({
  phone: [{ required: true, trigger: "blur", validator: phoneValidator }],
  smsCode: [{ required: true, trigger: "blur", message: "请输入手机验证码" }],
  newPassword: [
    { required: true, trigger: "blur", message: "请输入新密码" },
    { min: 6, max: 18, trigger: "blur", message: "密码长度为6到18位" },
  ],
});

// 封装手机验证规则
function isvalidPhone(phone: string) {
  const reg = /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/;
  return reg.test(phone);
}
// 手机号校验器 phoneValidator
function phoneValidator(rule: any, value: any, callback: any) {
  if (!value) {
    callback(new Error("请输入电话号码"));
  } else if (!isvalidPhone(value)) {
    //判断用户输入的值是否符合规则
    callback(new Error("请输入正确的11位手机号码"));
  } else {
    callback();
  }
}

function changePasswordTip(isShow: boolean) {
  isShowTip.value = isShow;
}

// 封装获取验证码函数
function getCaptcha() {
  getCaptchaApi().then(({ data }) => {
    const { verifyCodeBase64, verifyCodeKey } = data;
    captchaLogin.value.verifyCodeKey = verifyCodeKey;
    captchaBase64.value = verifyCodeBase64;
  });
}

//获取手机验证码接口函数
function getphoneCaptcha(data: phoneLoginDatato) {
  getPhoneCaptchaApi(data)
    .then((response) => {
      // 设置倒计时
      mobileCodeTimer.value = 60;
      let msgTimer = setInterval(() => {
        mobileCodeTimer.value = mobileCodeTimer.value - 1;
        if (mobileCodeTimer.value <= 0) {
          clearInterval(msgTimer);
        }
      }, 1000);
    })
    .catch(() => {
      // 重新获取验证码
      getCaptcha();
    });
}

// 校验规则  + 只校验一个
const getSmsCode = async () => {
  forgetFormRef.value.validateField(["phone"], async (valid: boolean) => {
    if (valid) {
      captchaLogin.value.phone = forgetData.value.phone;
      getphoneCaptcha(captchaLogin.value);
    } else {
      // 重新获取验证码
      getCaptcha();
      return false;
    }
  });
};

function handleReset() {
  forgetFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .forgetpassword(forgetData.value)
        .then((res) => {
          ElMessageBox.confirm("密码修改成功,请重新登录", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "success",
          }).then(() => {
            router.push("/login");
          });
        })
        .catch(() => {
          // 验证失败，重新生成验证码
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

function login() {
  router.push("/login");
}

// 开始就获取验证码
onMounted(() => {
  getCaptcha(); // 获取验证码
});
</script>

<style lang="scss" scoped>
.einput:not(:focus) + .poptip {
  transform: scale(1);
  animation: elastic-grow 0.25s;
}

.einput:focus + .poptip {
  transform: scale(0);
  animation: elastic-dec 0.45s;
}

.poptip {
  display: block;
  width: 236px;
  font-size: 13px;
  padding: 0.6em;
  background: #fafafa;
  position: absolute;
  margin-left: -3px;
  margin-bottom: -110px;
  border-radius: 2px;
  filter: drop-shadow(0 0 1px rgba(0, 0, 0, 0.23456));
  transform-origin: 15px -6px;
}
.poptip::before {
  content: "";
  position: absolute;
  top: -6px;
  left: 10px;
  border: 9px solid transparent;
  border-bottom-color: #fafafa;
  border-top-width: 0;
}
@keyframes elastic-grow {
  from {
    transform: scale(0);
  }
  70% {
    transform: scale(1.1);
    animation-timing-function: cubic-bezier(0.1, 0.25, 0.1, 0.25);
  }
}
@keyframes elastic-dec {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(0);
    animation-timing-function: cubic-bezier(0.25, 0.1, 0.25, 0.1);
  }
}

.login-bg {
  width: 100%;
  min-height: 100%;
  overflow: hidden;
  background: url("@/assets/login/bg.jpg") no-repeat;
  background-size: 100% 100%;
}

#login-box {
  display: flex;
  justify-content: space-between;
  position: absolute;
  top: 50%;
  left: 50%;
  height: 580px;
  transform: translateX(-50%) translateY(-50%);
  background-color: var(--el-bg-color);
  border-radius: 10px;
  overflow: hidden;
  box-shadow: var(--el-box-shadow);

  .login-banner {
    position: relative;
    width: 500px;
    background: url("@/assets/login/bg_login3.png") no-repeat;
    overflow: hidden;
    background-size: 100%;
    margin-top: 55px;
    .dark {
      position: absolute;
      top: 2;
      left: 2px;
    }

    .banner {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .captcha {
    position: absolute;
    top: 0;
    right: 0;

    img {
      border: 0.5px solid #dcdcdc;
      width: 100px;
      height: 48px;
      cursor: pointer;
    }
  }

  .login-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 500px;
    width: 500px;
    padding: 50px;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        font-size: 1.3em;
        color: var(--el-text-color-primary);
        margin: 0 auto 30px;
        font-weight: bold;
      }

      .zn {
        position: absolute;
        top: 0px;
        right: 0px;
      }
    }
  }

  .left {
    margin-right: 100px;
  }

  px .right {
    margin-right: 50px;
  }

  .el-form-item {
    margin-bottom: 24px;

    :deep(.el-input) {
      height: 48px;
      line-height: inherit;
      width: 100%;

      input {
        height: 48px;
      }

      .el-input__prefix,
      .el-input__suffix {
        display: flex;
        align-items: center;
      }

      .el-input__prefix {
        left: 10px;
      }

      .el-input__suffix {
        right: 10px;
      }
    }
  }

  .flex-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .sub-link {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    font-size: 14px;
    color: var(--el-text-color-secondary);

    .text {
      margin-right: 10px;
    }
  }
}

.copyright {
  position: absolute;
  bottom: 30px;
  width: 100%;
  margin: 0;
}
</style>
